package com.adminserver.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.adminserver.entity.ApplyMaterialEntity;
import com.adminserver.mapper.ApplyMaterialMapper;
import com.adminserver.service.ApplyMaterialService;
import com.adminserver.service.RepairOrdersService;
import com.adminserver.service.WorkerService;
import com.adminserver.util.DateGenerator.DateGenerator;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/financial")
public class FinancialController {

    @Autowired
    ApplyMaterialService applyMaterialService;

    @Autowired
    ApplyMaterialMapper applyMaterialMapper;

    @Autowired
       WorkerService workerService;

    @Autowired
    RepairOrdersService repairOrdersService;

    @GetMapping("/yearSpendingAndIncomeFinancial")
    public ResponseUtil yearSpendingAndIncomeFinancial(@RequestParam int year) {
        List<ApplyMaterialEntity> applyMaterialEntities = applyMaterialService.yearSpendingAndIncomeFinancial(year);
        double totalSpending = 0;
        double totalIncome = 0;
        for (ApplyMaterialEntity item : applyMaterialEntities) {
            double temp = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
            totalIncome += temp;
            if (item.getChargeOn()) totalSpending += temp;
        }
        HashMap<String, Double> map = new HashMap<>();
        map.put("totalIncome", NumberUtil.round(totalIncome, 1).doubleValue());
        map.put("totalSpending", NumberUtil.round(totalSpending, 1).doubleValue());
        return ResponseUtil.setE(ResponseEnum.OK).setData(map);
    }

    @GetMapping("/yearSpendingRate")
    public ResponseUtil yearSpendingRate() {
        List<Map<String, Object>> spending = new ArrayList<>();
        List<Map<String, Object>> income = new ArrayList<>();

        /**
         * 数据结构：
         * {
         *      spending:[
         *          { date:"", title:"" }
         *      ],
         *      income:[
         *          { date:"", title:"" }
         *      ]
         * }
         */

        {
            // 去年的同比增长率
            DateTime lastYear = DateUtil.date().offset(DateField.YEAR, -1);
            DateTime lastTwoYear = DateUtil.date().offset(DateField.YEAR, -2);
            String[] lastYear_yearBeginEndTime = DateGenerator.getYearBeginEndTime(lastYear.year());
            String[] lastTwoYear_yearBeginEndTime = DateGenerator.getYearBeginEndTime(lastTwoYear.year());
            List<ApplyMaterialEntity> lastYearList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(lastYear_yearBeginEndTime[0], lastYear_yearBeginEndTime[1]);
            List<ApplyMaterialEntity> lastTwoYearList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(lastTwoYear_yearBeginEndTime[0], lastTwoYear_yearBeginEndTime[1]);
            double lastYearTotalSpending = 0, lastTwoYearTotalSpending = 0;
            double lastYearTotalIncome = 0, lastTwoYearTotalIncome = 0;
            for (ApplyMaterialEntity item : lastYearList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                lastYearTotalSpending += value;
                if (item.getChargeOn()) lastYearTotalIncome += value;
            }
            for (ApplyMaterialEntity item : lastTwoYearList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                lastTwoYearTotalSpending += value;
                if (item.getChargeOn()) lastTwoYearTotalIncome += value;
            }
            String lastYearSpendingGrowthRate =  NumberUtil.decimalFormat("###.##%",0);
            if (lastTwoYearTotalSpending != 0)
                lastYearSpendingGrowthRate = NumberUtil.decimalFormat("###.##%", NumberUtil.round(NumberUtil.div((lastYearTotalSpending - lastTwoYearTotalSpending), lastTwoYearTotalSpending), 3).doubleValue());
            String lastYearIncomeGrowthRate = NumberUtil.decimalFormat("###.##%", 0);
            if (lastTwoYearTotalIncome != 0)
                lastYearIncomeGrowthRate = NumberUtil.decimalFormat("###.##%", NumberUtil.round(NumberUtil.div((lastYearTotalIncome - lastTwoYearTotalIncome), lastTwoYearTotalIncome), 3).doubleValue());
            System.out.println(lastYear.year() + "年报修支出同比增长率：" + lastYearSpendingGrowthRate);
            System.out.println(lastYear.year() + "年报修收入同比增长率：" + lastYearIncomeGrowthRate);

            HashMap<String, Object> map = new HashMap<>();
            map.put("data", lastYearSpendingGrowthRate);
            map.put("title", lastYear.year() + "年报修支出同比增长率");
            spending.add(map);

            map = new HashMap<>();
            map.put("data", lastYearIncomeGrowthRate);
            map.put("title", lastYear.year() + "年报修收入同比增长率");
            income.add(map);
        }


        {
            // 今年上月环比增长率
            int year = DateUtil.date().year();
            int lastMonth = DateUtil.date().offset(DateField.MONTH, -1).month();
            int lastTwoMonth = DateUtil.date().offset(DateField.MONTH, -2).month();
            String[] lastMonthBeginEndTime = DateGenerator.getYearInMonthBeginEndTime(year, lastMonth);
            String[] lastTwoMonthBeginEndTime = DateGenerator.getYearInMonthBeginEndTime(year, lastTwoMonth);
            List<ApplyMaterialEntity> lastMonthBeginEndList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(lastMonthBeginEndTime[0], lastMonthBeginEndTime[1]);
            List<ApplyMaterialEntity> lastTwoMonthBeginEndList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(lastTwoMonthBeginEndTime[0], lastTwoMonthBeginEndTime[1]);
            double lastMonthTotalSpending = 0;
            double lastTwoMonthTotalSpending = 0;
            double lastMonthTotalIncome = 0;
            double lastTwoMonthTotalIncome = 0;
            for (ApplyMaterialEntity item : lastMonthBeginEndList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                lastMonthTotalSpending += value;
                if (item.getChargeOn()) lastMonthTotalIncome += value;
            }
            for (ApplyMaterialEntity item : lastTwoMonthBeginEndList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                lastTwoMonthTotalSpending += value;
                if (item.getChargeOn()) lastTwoMonthTotalIncome += value;
            }
            String lastMonthSpendingGrowthRate = NumberUtil.decimalFormat("###.##%",0);
            if (lastTwoMonthTotalSpending != 0)
                lastMonthSpendingGrowthRate = NumberUtil.decimalFormat("###.##%", NumberUtil.round(NumberUtil.div((lastMonthTotalSpending - lastTwoMonthTotalSpending), lastTwoMonthTotalSpending), 3).doubleValue());
            String lastMonthIncomeGrowthRate = NumberUtil.decimalFormat("###.##%",0);
            if (lastTwoMonthTotalIncome != 0)
                lastMonthIncomeGrowthRate = NumberUtil.decimalFormat("###.##%", NumberUtil.round(NumberUtil.div((lastMonthTotalIncome - lastTwoMonthTotalIncome), lastTwoMonthTotalIncome), 3).doubleValue());
            System.out.println(year + "年" + (lastMonth + 1) + "月报修环比支出增长率：" + lastMonthSpendingGrowthRate);
            System.out.println(year + "年" + (lastMonth + 1) + "月报修环比收入增长率：" + lastMonthIncomeGrowthRate);

            HashMap<String, Object> map = new HashMap<>();
            map.put("data", lastMonthSpendingGrowthRate);
            map.put("title", year + "年" + (lastMonth + 1) + "月报修支出环比增长率");
            spending.add(map);

            map = new HashMap<>();
            map.put("data", lastMonthIncomeGrowthRate);
            map.put("title", year + "年" + (lastMonth + 1) + "月报修收入环比增长率");
            income.add(map);
        }

        {
            // 2018-2021年均增长量及增长率
            int[] years = new int[2];
            years[0] = DateUtil.date().offset(DateField.YEAR, -1).year();
            years[1] = DateUtil.date().offset(DateField.YEAR, -4).year();
            String[] currentYear = DateGenerator.getYearBeginEndTime(years[0]);
            String[] baseYear = DateGenerator.getYearBeginEndTime(years[1]);
            List<ApplyMaterialEntity> currentYearList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(currentYear[0], currentYear[1]);
            List<ApplyMaterialEntity> baseYearList = applyMaterialMapper.queryMaterialPriceAndTakeAmountAndChargeOnByApplyTimeBetween(baseYear[0], baseYear[1]);
            double currentYearTotalSpending = 0, baseYearTotalSpending = 0;
            double currentYearTotalIncome = 0, baseYearTotalIncome = 0;
            for (ApplyMaterialEntity item : currentYearList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                currentYearTotalSpending += value;
                if (item.getChargeOn()) currentYearTotalIncome += value;
            }
            for (ApplyMaterialEntity item : baseYearList) {
                double value = NumberUtil.mul(item.getMaterialPrice(), item.getTakeAmount()).doubleValue();
                baseYearTotalSpending += value;
                if (item.getChargeOn()) baseYearTotalIncome += value;
            }
            double yearAverageSpendingGrowthIncrease = 0, yearAverageIncomeGrowthIncrease = 0;
            if (baseYearTotalSpending != 0)
                yearAverageSpendingGrowthIncrease = NumberUtil.round(NumberUtil.div(NumberUtil.sub(currentYearTotalSpending, baseYearTotalSpending), baseYearTotalSpending), 3).doubleValue();
            if (baseYearTotalIncome != 0)
                yearAverageIncomeGrowthIncrease = NumberUtil.round(NumberUtil.div(NumberUtil.sub(currentYearTotalIncome, baseYearTotalIncome), baseYearTotalIncome), 3).doubleValue();
            System.out.println(years[1] + "-" + years[0] + "年报修支出年均增长量：" + yearAverageSpendingGrowthIncrease);
            System.out.println(years[1] + "-" + years[0] + "年报修收入年均增长量：" + yearAverageIncomeGrowthIncrease);

            double v = 0;
            if (baseYearTotalSpending != 0)
            v = NumberUtil.div(currentYearTotalSpending, baseYearTotalSpending);
            double n = 1d / (years[0] - years[1]);
            String yearAverageSpendingGrowthRate = NumberUtil.decimalFormat("###.##%", Math.pow(v, n) - 1);
            System.out.println(years[1] + "-" + years[0] + "年报修支出年均增长率：" + yearAverageSpendingGrowthRate);

            if (baseYearTotalIncome != 0){
                v = NumberUtil.div(currentYearTotalIncome, baseYearTotalIncome);
            }else{
                v = 0;
            }
            n = 1d / (years[0] - years[1]);
            String yearAverageIncomeGrowthRate = NumberUtil.decimalFormat("###.##%", Math.pow(v, n) - 1);
            System.out.println(years[1] + "-" + years[0] + "年报修收入年均增长率：" + yearAverageIncomeGrowthRate);


            HashMap<String, Object> map = new HashMap<>();
            map.put("data", yearAverageSpendingGrowthIncrease);
            map.put("title", years[1] + "-" + years[0] + "年报修支出年均增长量");
            spending.add(map);

            map = new HashMap<>();
            map.put("data", yearAverageIncomeGrowthIncrease);
            map.put("title", years[1] + "-" + years[0] + "年报修收入年均增长量");
            income.add(map);

            map = new HashMap<>();
            map.put("data", yearAverageSpendingGrowthRate);
            map.put("title", years[1] + "-" + years[0] + "年报修支出年均增长率");
            spending.add(map);

            map = new HashMap<>();
            map.put("data", yearAverageIncomeGrowthRate);
            map.put("title", years[1] + "-" + years[0] + "年报修收入年均增长率");
            income.add(map);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("spending", spending);
        result.put("income", income);
        return ResponseUtil.setE(ResponseEnum.OK).setData(result);
    }


    /**
     * 维修员工资分析
     * @return
     */
    @GetMapping("/workerWageAnalyse")
    public ResponseUtil workerWageAnalyse(@RequestParam int year, @RequestParam int month) {
        // 在岗员工
        int workerCount = workerService.count();
        // 月员工工资-总支出 -- 一般为上月
        if (year > DateUtil.date().year() || month >= DateUtil.date().month() + 1){
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("查询失败, 年月错误");
        }
        String[] yearInMonthBeginEndTime = DateGenerator.getYearInMonthBeginEndTime(year, month);

        // 月员工工资-平均工资
        // 月员工工资-最高工资
        // 月员工工资-最低工资
        // 月员工工资-总支出环比增长率

        return ResponseUtil.setE(ResponseEnum.OK).setData(null);
    }
}
